<template>
  <div>
    <el-input
        v-if="editing"
        v-model="value"
        size="small"
        @blur="saveEdit"
        @keyup.enter="saveEdit"
        ref="input"
    ></el-input>
    <div v-else @click="enableEdit">
      {{ value }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'EditableCell',
  props: {
    value: {
      type: [String, Number, null],
      required: true,
    },
  },
  data() {
    return {
      editing: false,
      tempValue: this.value,
    }
  },
  watch: {
    value(newVal) {
      this.tempValue = newVal
    }
  },
  methods: {
    enableEdit() {
      this.editing = true
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    },
    saveEdit() {
      this.editing = false
      this.$emit('input', this.tempValue) // v-model 双向绑定
    },
  },
  computed: {
    value: {
      get() {
        return this.tempValue
      },
      set(val) {
        this.tempValue = val
      },
    },
  },
}
</script>
